var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
//var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var multer = require('multer');
// log4js config
var logHelper = require('./server/utils/logHelper');

var app = express();

var fs = require('fs');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//////// log4j config
logHelper.use(app);

logHelper.helper.writeLogTodo("重启动了"+new Date().toLocaleString())
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'uploads')));
// 允许来自不同域名的请求
app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
    next();
})

// session config
app.use(session({
    secret: 'wx-atvillage',
    resave: false,
    cookie: {maxAge: null},
    saveUninitialized: true
}));

// main routes
// 需要放在log4js后面引入
var mainRoute = require('./routes/mainRoute');
// 路由总入口
mainRoute(app);
//app.use(function(req, res, next) {
//  console.log(req.sessionID);
//  console.log(req.session.id);
//  res.send({});
//});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    // next(err);
    next(null);
});

// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        console.error(err.stack);

        //res.render('error', {
        //  message: err.message,
        //  error: err
        //});
        res.send({
            message: err.message
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    //res.render('error', {
    //  message: err.message,
    //  error: {}
    //});
    console.error(err.stack);

    res.send({
        message: err.message
    });
});


app.use(express.static(path.join(__dirname, 'uploads')));

//uplaod config
app.use(multer({
    //dest: './uploads/images',
    dest: './uploads',
    limits: {

    },
    rename: function(fieldname, filename,  req, res) {
        var uplaodTypeId = req.body.utypeid+""; //类型编号

        if(uplaodTypeId=='1001') { //上传用户头像
            return 'hp-' + Date.now();
        } else if(uplaodTypeId=='1002') { //修改村落图片名称
            return 'region-' + Date.now();
        } else if(uplaodTypeId=='1003') { //修改活动图片名称
            return 'events-' + Date.now();
        } else if(uplaodTypeId=='1004') {
            return 'temper-'+ Date.now();
        } else {
            return 'images-' + Date.now();
        }
    },
    changeDest: function(dest, req, res) {
        var uplaodTypeId = req.body.utypeid+""; //类型编号

        if(uplaodTypeId=='1001') { //上传用户头像
            dest += '/portraits';
        } else if(uplaodTypeId=='1002') { //上传村落图片
            dest += '/villages';
        } else if(uplaodTypeId=='1003') { //上传村落图片
            dest += '/events';
        } else if(uplaodTypeId=='1004') { // 状态图片
            dest += '/temper';
        } else {
            dest += '/images';
        }

        //目录不存在则创建改目录
        fs.existsSync(dest) || fs.mkdirSync(dest);

        return dest;
    },
    onFileUploadStart: function(file, req, res) { //是否上传文件
        var uplaodTypeId = req.body.utypeid;
        //console.log("3:",req.body,file);
        return true;
    },
    onParseEnd: function (req, next) {
        //console.log('Form parsing completed at: ', new Date());

        // usage example: custom body parse
        //req.body = require('qs').parse(req.body);
        // call the next middleware
        next();
    },
    onError: function (error, next) {
        console.log('upload error:'+ error)
        next(error)
    }
}));

Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}
//process.on('uncaughtException', function (err) {
//    console.log('Caught exception: ' + err);
//});
Object.prototype.clone = function() {
    var copy = (this instanceof Array) ? [] : {};
    for (attr in this) {
        if (!obj.hasOwnProperty(attr)) continue;
        copy[attr] = (typeof this[i] == "object")?obj[attr].clone():obj[attr];
    }
    return copy;
};

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

module.exports = app;
